package com.woniu.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.common.dto.LoginDto;
import com.woniu.common.entity.AdmAccount;
import com.woniu.common.entity.AdmCustomer;
import com.woniu.common.entity.Result;
import com.woniu.customer.configuration.JwtUtils;
import com.woniu.customer.mapper.AccountMapper;
import com.woniu.customer.mapper.LoginMapper;
import com.woniu.customer.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    LoginMapper loginMapper;
    @Autowired
    AccountMapper accountMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;
    //  用户登录
    @Override
    public Result login(LoginDto loginDto, HttpServletResponse response) {
        //  通过key从redis获取存储验证码
        String verifycode = (String) redisTemplate.opsForValue().get("emailcode:"+loginDto.getAaname());
        System.out.println("redis中的验证码："+verifycode);
        //  判断验证码是否正确
        if (loginDto.getVerifyCode() == null || !verifycode.equals(loginDto.getVerifyCode())) {
            return new Result(403,"验证码错误",null);
        }else if (verifycode.equals(loginDto.getVerifyCode())) {
            try{
                String pwd = "yl" + loginDto.getAaname();
                System.out.println("密码1："+pwd);
                String password = DigestUtils.md5DigestAsHex(pwd.getBytes());
                System.out.println("密码1："+password);
                //  创建用户名密码token
                UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginDto.getAaname(), password);
                System.out.println("用户名密码token："+usernamePasswordToken);
                //  获取subject
                Subject subject = SecurityUtils.getSubject();
                //  登录
                subject.login(usernamePasswordToken);
                //  生成token
                String salt = "12345";  //  设置密钥盐
                String newToken = JwtUtils.sign(loginDto.getAaname(), salt, 3600);
                //  将token存入redis
                redisTemplate.opsForValue().set("usertoken:" + loginDto.getAaname(), newToken);
                String acid = String.valueOf(getCustomerByEmail(loginDto.getAaname()).getAcid());
                //  设置key为x-auth-token的数据可以被前端JavaScript获取
                response.setHeader("Access-Control-Expose-Headers", "xu-auth-token, userid");
                //  将token存入响应头
                response.setHeader("xu-auth-token", newToken);
                response.setHeader("userid", acid);
                return Result.ok("登录成功！");
            }catch (AuthenticationException e) {
                return new Result(202,"进入注册",null);
//                throw e;
            } catch (IllegalStateException e ){
                return Result.fail("请登录！");
            }catch (Exception e) {
                throw e;
            }
        }
        return Result.fail("登录失败！");
    }
    //  根据邮箱查询客户
    @Override
    public AdmCustomer getCustomerByEmail(String email) {
        return loginMapper.selectOne(new QueryWrapper<AdmCustomer>().eq("email", email));
    }

    //  获取上次token生成时的salt值和登录用户信息
    public AdmCustomer getJwtTokenInfo(String email) {
        String salt = "12345";
        AdmCustomer admCustomer = getCustomerByEmail(email);
        return admCustomer;
    }
    //  向邮箱发送验证码
    @Override
    public Result sendEmail(String email,String code) {
        String message = email + ";" + code;
        rabbitTemplate.convertAndSend("verifyExchange","verifymail", message);
        return null;
    }
    //  注册用户
    @Override
    public void addCustomer(AdmCustomer admCustomer) {
//        // 截取身份证号中的出生日期
//        LocalDate birthDate = LocalDate.parse(admCustomer.getIdcard().substring(6, 14));
//        // 计算年龄
//        int age = Period.between(birthDate, LocalDate.now()).getYears();
//        admCustomer.setAge(age);
        System.out.println(admCustomer);
        //  获取默认昵称
        String uuid = UUID.randomUUID().toString();
        String user = uuid.substring(0, 4) + "_" + uuid.substring(4, 10);
        admCustomer.setUser(user);

        admCustomer.setCreatetime1(LocalDate.now());
        admCustomer.setCreatetime2(LocalDate.now());
        loginMapper.insert(admCustomer);
        AdmAccount admAccount = new AdmAccount();
        admAccount.setAauser(user);
        admAccount.setAaname(admCustomer.getName());
        admAccount.setAaemail(admCustomer.getEmail());
        admAccount.setAatype("客户");
        accountMapper.insert(admAccount);
    }
    //  根据id查询用户
    @Override
    public AdmCustomer getCustomerById(int id) {
        return loginMapper.selectOne(new QueryWrapper<AdmCustomer>().eq("acid", id));
    }
}
